import Picker from "emoji-picker-react";
import {
  TextField,
  Thumbnail,
  Button,
  Icon,
  Tooltip,
  Popover,
  Listbox,
  Link,
  AutoSelection,
  Scrollable,
  EmptySearchResult,
  Text,
  DropZone,
  LegacyStack,
  OptionList,
  LegacyCard,
} from "@shopify/polaris";
import { useState, useCallback } from "react";
import "./App.css";
import styled from "./index.module.less";
import {
  AttachmentMajor,
  HashtagMajor,
  SmileyHappyMajor,
  MentionMajor,
  SearchMinor,
  NoteMinor,
  CustomersMajor,
  OrdersMinor,
  ProductsMinor,
  ChecklistAlternateMajor,
  ChevronRightMinor,
  MobileCancelMajor,
} from "@shopify/polaris-icons";
import Searchs from "../../../../../../components/Search";

const actionValue = "__ACTION__";

const segments = [
  {
    label: "sheneriodesign",
    id: "gid://shopify/CustomerSegment/1",
    value: "0",
    img: "https://burst.shopifycdn.com/photos/black-leather-choker-necklace_373x@2x.jpg",
  },
];

const interval = 25;

const App = () => {
  const [numbers, setNumbers] = useState(false);
  const [chosenEmoji, setChosenEmoji] = useState(null as any);

  const onEmojiClick = (event: any, emojiObject: any) => {
    {
      // console.log(event);
      setChosenEmoji(emojiObject);
      setValue(value + event.emoji);
    }
  };

  const [show, setShow] = useState(false);

  // const [value, setValue] = useState([] as any[]);

  const [value, setValue] = useState("");

  const handleChange = useCallback(
    (newValue: any) => setValue(newValue.target.value),
    []
  );

  //Popover 表情
  const [popoverActive, setPopoverActive] = useState(false);

  const togglePopoverActive = useCallback(
    () => setPopoverActive((popoverActive) => !popoverActive),
    []
  );

  const activator = (
    <Tooltip content="添加表情符号">
      <div
        style={{ margin: "0 5px", cursor: "pointer" }}
        onClick={togglePopoverActive}
      >
        <Icon source={SmileyHappyMajor} color="subdued"></Icon>
      </div>
    </Tooltip>
  );
  //Popover 提及员工
  const [popoverActiveTJYG, setPopoverActiveTJYG] = useState(false);

  const togglePopoverActiveTJYG = useCallback(
    () => setPopoverActiveTJYG((popoverActiveTJYG) => !popoverActiveTJYG),
    []
  );

  const activatorTJYG = (
    <Tooltip content="提及员工">
      <div
        style={{ margin: "0 5px", cursor: "pointer" }}
        onClick={togglePopoverActiveTJYG}
      >
        <Icon source={MentionMajor} color="subdued"></Icon>
      </div>
    </Tooltip>
  );
  //Popover 参考页面
  const [popoverActiveCKYM, setPopoverActiveCKYM] = useState(false);

  const togglePopoverActiveCKYM = useCallback(() => {
    setPopoverActiveCKYM((popoverActiveCKYM) => !popoverActiveCKYM);
    setNumbers(false);
  }, []);

  const activatorCKYM = (
    <Tooltip content="参考页面">
      <div
        style={{ margin: "0 5px", cursor: "pointer" }}
        onClick={togglePopoverActiveCKYM}
      >
        <Icon source={HashtagMajor} color="subdued"></Icon>
      </div>
    </Tooltip>
  );
  const [selectedCKYM, setSelectedCKYM] = useState<string[]>([]);

  //上传文件
  const [files, setFiles] = useState<File[]>([]);

  const handleDropZoneDrop = useCallback(
    (_dropFiles: File[], acceptedFiles: File[], _rejectedFiles: File[]) => {
      setFiles((files) => [...files, ...acceptedFiles]);
    },
    []
  );

  const validImageTypes = ["image/gif", "image/jpeg", "image/png"];

  const fileUpload = !files.length && <DropZone.FileUpload />;
  const uploadedFiles = files.length > 0 && (
    <div style={{ padding: "0" }}>
      <LegacyStack vertical>
        <div style={{ display: "flex", width: "100%", flexWrap: "wrap" }}>
          {files.map((file, index) => (
            <div
              key={index}
              style={{ width: "190px", height: "70px", marginRight: "8px" }}
            >
              <LegacyCard key={index} sectioned title="">
                <div
                  style={{ display: "flex", width: "160px", height: "40px" }}
                >
                  <div>
                    <Thumbnail
                      size="small"
                      alt={file.name}
                      source={
                        validImageTypes.includes(file.type)
                          ? window.URL.createObjectURL(file)
                          : NoteMinor
                      }
                    />
                  </div>
                  <div style={{ marginLeft: "10px" }}>
                    {file.name}
                    <Text variant="bodySm" as="p">
                      {file.size} bytes
                    </Text>
                  </div>
                  <div
                    style={{ marginLeft: "8px", cursor: "pointer" }}
                    onClick={() => {
                      const asbfcl = files;
                      asbfcl.splice(index, 1);
                      setFiles([...asbfcl]);
                    }}
                  >
                    <Icon source={MobileCancelMajor}></Icon>
                  </div>
                </div>
              </LegacyCard>
            </div>
          ))}
        </div>
      </LegacyStack>
    </div>
  );

  //SEARCH
  const [showFooterAction, setShowFooterAction] = useState(false);
  const [query, setQuery] = useState<string>("");
  const [lazyLoading, setLazyLoading] = useState(false);
  const [willLoadMoreResults, setWillLoadMoreResults] = useState(true);
  const [visibleOptionIndex, setVisibleOptionIndex] = useState(6);
  const [activeOptionId, setActiveOptionId] = useState(segments[0].id);
  const [selectedSegmentIndex, setSelectedSegmentIndex] = useState(0);
  const [filteredSegments, setFilteredSegments] = useState<
    (typeof segments)[number][]
  >([]);

  const handleClickShowAll = () => {
    setShowFooterAction(false);
    setVisibleOptionIndex(segments.length);
  };

  const handleFilterSegments = (query: any) => {
    const nextFilteredSegments = segments.filter((segment) => {
      return segment.label
        .toLocaleLowerCase()
        .includes(query.toLocaleLowerCase().trim());
    });

    setFilteredSegments(nextFilteredSegments);
  };

  const handleQueryChange = (query: any) => {
    setQuery(query);

    if (query.length >= 2) handleFilterSegments(query);
  };

  const handleQueryClear = () => {
    handleQueryChange("");
  };

  const handleSegmentSelect = (segmentIndex: string) => {
    if (segmentIndex === actionValue) {
      return handleClickShowAll();
    }

    setSelectedSegmentIndex(Number(segmentIndex));

    setValue(value + segments[Number(segmentIndex)].label + " ");

    setPopoverActiveTJYG(false);
  };

  const handleActiveOptionChange = (_: string, domId: string) => {
    setActiveOptionId(domId);
  };

  const handleLazyLoadSegments = () => {
    if (willLoadMoreResults && !showFooterAction) {
      setLazyLoading(true);

      const options = query ? filteredSegments : segments;

      setTimeout(() => {
        const remainingOptionCount = options.length - visibleOptionIndex;
        const nextVisibleOptionIndex =
          remainingOptionCount >= interval
            ? visibleOptionIndex + interval
            : visibleOptionIndex + remainingOptionCount;

        setLazyLoading(false);
        setVisibleOptionIndex(nextVisibleOptionIndex);

        if (remainingOptionCount <= interval) {
          setWillLoadMoreResults(false);
        }
      }, 1000);
    }
  };

  const listboxId = "SearchableListbox";

  const textFieldMarkup = (
    <div style={{ padding: "12px" }}>
      <TextField
        // focused={showFooterAction}
        clearButton
        labelHidden
        label=""
        placeholder="搜索"
        autoComplete="off"
        value={query}
        prefix={<Icon source={SearchMinor} />}
        ariaActiveDescendant={activeOptionId}
        ariaControls={listboxId}
        onChange={handleQueryChange}
        onClearButtonClick={handleQueryClear}
      />
    </div>
  );

  const segmentOptions = query ? filteredSegments : segments;

  const segmentList =
    segmentOptions.length > 0
      ? segmentOptions
          .slice(0, visibleOptionIndex)
          .map(({ label, id, value, img }) => {
            const selected = segments[selectedSegmentIndex].value === value;
            return (
              <Listbox.Option key={id} value={value} selected={selected}>
                <Listbox.TextOption selected={selected}>
                  <div style={{ display: "flex", alignItems: "center" }}>
                    <div>
                      <Thumbnail
                        source={img}
                        size="extraSmall"
                        alt="Black choker necklace"
                      />
                    </div>
                    <div style={{ marginLeft: "5px" }}>{label}</div>
                  </div>
                </Listbox.TextOption>
              </Listbox.Option>
            );
          })
      : null;

  const listboxMarkup = (
    <Listbox
      enableKeyboardControl
      autoSelection={AutoSelection.FirstSelected}
      accessibilityLabel="Search for and select a customer segment"
      customListId={listboxId}
      onSelect={handleSegmentSelect}
      onActiveOptionChange={handleActiveOptionChange}
    >
      {segmentList}
      {/* {showAllMarkup} */}
      {/* {noResultsMarkup} */}
      {/* {lazyLoadingMarkup} */}
    </Listbox>
  );

  return (
    <div>
      <div>
        <div style={{ display: "flex", alignItems: "center" }}>
          <div style={{ width: "40px" }}>
            <Thumbnail
              source="https://burst.shopifycdn.com/photos/black-leather-choker-necklace_373x@2x.jpg"
              size="small"
              alt="Black choker necklace"
            />
          </div>
          <div style={{ flex: "1" }}>
            <input
              className={styled.ipt}
              placeholder="发表评论......"
              type="text"
              value={value}
              onChange={handleChange}
            />
          </div>
        </div>
        {uploadedFiles && (
          <div style={{ marginTop: "10px" }}>
            {uploadedFiles}
            {/* {fileUpload} */}
          </div>
        )}
      </div>
      <div
        style={{
          paddingTop: "10px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <div style={{ display: "flex" }}>
          <Popover
            active={popoverActive}
            activator={activator}
            autofocusTarget="first-node"
            onClose={togglePopoverActive}
          >
            <Picker onEmojiClick={onEmojiClick} />
          </Popover>
          <Popover
            active={popoverActiveTJYG}
            activator={activatorTJYG}
            autofocusTarget="first-node"
            onClose={togglePopoverActiveTJYG}
          >
            <div
              style={{
                alignItems: "stretch",
                borderTop: "1px solid #DFE3E8",
                display: "flex",
                flexDirection: "column",
                justifyContent: "stretch",
                position: "relative",
                width: "100%",
                height: "100%",
                overflow: "hidden",
              }}
            >
              {textFieldMarkup}
              <Scrollable
                shadow
                style={{
                  position: "relative",
                  padding: "var(--p-space-2) 0",
                  borderBottomLeftRadius: "var(--p-border-radius-2)",
                  borderBottomRightRadius: "var(--p-border-radius-2)",
                }}
                onScrolledToBottom={handleLazyLoadSegments}
              >
                {listboxMarkup}
              </Scrollable>
            </div>
          </Popover>
          <Popover
            active={popoverActiveCKYM}
            activator={activatorCKYM}
            autofocusTarget="first-node"
            onClose={togglePopoverActiveCKYM}
          >
            {!numbers && (
              <OptionList
                title=""
                onChange={setSelectedCKYM}
                options={[
                  {
                    value: "DD",
                    label: (
                      <div
                        className={styled.OSDQWD}
                        onClick={() => {
                          setNumbers(true);
                        }}
                      >
                        <div className={styled.VHIYAB}>
                          <div>
                            <Icon source={OrdersMinor} color="subdued"></Icon>
                          </div>
                          <div className={styled.BIDAWSA}>订单</div>
                        </div>
                        <div className={styled.VHIYAB}>
                          <div className={styled.AGUISF}>#</div>
                          <div className={styled.AGUISF}>O</div>
                          <div>
                            <Icon
                              color="subdued"
                              source={ChevronRightMinor}
                            ></Icon>
                          </div>
                        </div>
                      </div>
                    ),
                  },
                  {
                    value: "CGDD",
                    label: (
                      <div className={styled.OSDQWD}>
                        <div className={styled.VHIYAB}>
                          <div>
                            <div style={{ visibility: "hidden" }}>
                              <Icon
                                source={AttachmentMajor}
                                color="subdued"
                              ></Icon>
                            </div>
                          </div>
                          <div className={styled.BIDAWSA + " " + styled.JADBFC}>
                            草稿订单
                          </div>
                        </div>
                        <div className={styled.VHIYAB}>
                          <div className={styled.AGUISF}>#</div>
                          <div className={styled.AGUISF}>D</div>
                          <div>
                            <Icon
                              color="subdued"
                              source={ChevronRightMinor}
                            ></Icon>
                          </div>
                        </div>
                      </div>
                    ),
                  },
                  {
                    value: "KH",
                    label: (
                      <div className={styled.OSDQWD}>
                        <div className={styled.VHIYAB}>
                          <div>
                            <Icon
                              source={CustomersMajor}
                              color="subdued"
                            ></Icon>
                          </div>
                          <div className={styled.BIDAWSA}>客户</div>
                        </div>
                        <div className={styled.VHIYAB}>
                          <div className={styled.AGUISF}>#</div>
                          <div className={styled.AGUISF}>C</div>
                          <div>
                            <Icon
                              color="subdued"
                              source={ChevronRightMinor}
                            ></Icon>
                          </div>
                        </div>
                      </div>
                    ),
                  },
                  {
                    value: "CP",
                    label: (
                      <div className={styled.OSDQWD}>
                        <div className={styled.VHIYAB}>
                          <div>
                            <Icon source={ProductsMinor} color="subdued"></Icon>
                          </div>
                          <div className={styled.BIDAWSA}>产品</div>
                        </div>
                        <div className={styled.VHIYAB}>
                          <div className={styled.AGUISF}>#</div>
                          <div className={styled.AGUISF}>P</div>
                          <div>
                            <Icon
                              color="subdued"
                              source={ChevronRightMinor}
                            ></Icon>
                          </div>
                        </div>
                      </div>
                    ),
                  },
                  {
                    value: "DSX",
                    label: (
                      <div className={styled.OSDQWD}>
                        <div className={styled.VHIYAB}>
                          <div>
                            <div style={{ visibility: "hidden" }}>
                              <Icon
                                source={AttachmentMajor}
                                color="subdued"
                              ></Icon>
                            </div>
                          </div>
                          <div className={styled.BIDAWSA}>多属性</div>
                        </div>
                        <div className={styled.VHIYAB}>
                          <div className={styled.AGUISF}>#</div>
                          <div className={styled.AGUISF}>V</div>
                          <div>
                            <Icon
                              color="subdued"
                              source={ChevronRightMinor}
                            ></Icon>
                          </div>
                        </div>
                      </div>
                    ),
                  },
                  {
                    value: "ZY",
                    label: (
                      <div className={styled.OSDQWD}>
                        <div className={styled.VHIYAB}>
                          <div>
                            <Icon
                              source={ChecklistAlternateMajor}
                              color="subdued"
                            ></Icon>
                          </div>
                          <div className={styled.BIDAWSA}>转移</div>
                        </div>
                        <div className={styled.VHIYAB}>
                          <div className={styled.AGUISF}>#</div>
                          <div className={styled.AGUISF}>T</div>
                          <div>
                            <Icon
                              color="subdued"
                              source={ChevronRightMinor}
                            ></Icon>
                          </div>
                        </div>
                      </div>
                    ),
                  },
                  {
                    value: "CGDDs",
                    label: (
                      <div className={styled.OSDQWD}>
                        <div className={styled.VHIYAB}>
                          <div>
                            <Icon
                              source={ChecklistAlternateMajor}
                              color="subdued"
                            ></Icon>
                          </div>
                          <div className={styled.BIDAWSA}>采购订单</div>
                        </div>
                        <div className={styled.VHIYAB}>
                          <div className={styled.AGUISF}>#</div>
                          <div className={styled.AGUISF}>P</div>
                          <div className={styled.AGUISF}>O</div>
                          <div>
                            <Icon
                              color="subdued"
                              source={ChevronRightMinor}
                            ></Icon>
                          </div>
                        </div>
                      </div>
                    ),
                  },
                ]}
                selected={selectedCKYM}
              />
            )}
            {numbers && (
              <Searchs
                value={value}
                setValue={setValue}
                close={setPopoverActiveCKYM}
              />
            )}
          </Popover>
          <div style={{ visibility: "hidden", width: "30px", height: "0px" }}>
            <DropZone onDrop={handleDropZoneDrop}>
              {/* {uploadedFiles} */}
              {/* {fileUpload} */}
              <div style={{ visibility: "visible", marginTop: "-25px" }}>
                <Tooltip content="附加文件">
                  <div
                    style={{ margin: "0 5px", cursor: "pointer" }}
                    onClick={() => {}}
                  >
                    <Icon source={AttachmentMajor} color="subdued"></Icon>
                  </div>
                </Tooltip>
              </div>
            </DropZone>
          </div>
          {/* <input type="file" /> */}
        </div>
        <div>
          {!value && (
            <Button size="slim" disabled>
              发布
            </Button>
          )}
          {value && <Button size="slim">发布</Button>}
        </div>
      </div>
    </div>
  );
};
export default App;
